import tkinter as tk
from tkinter import filedialog, messagebox
import subprocess
import ctypes
import sys
import os

# 定义一个函数来检查是否有足够的权限
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

# 定义一个函数来重新启动脚本以管理员权限运行
def restart_as_admin():
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

class RobocopyGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Robocopy GUI")
        self.root.geometry("450x550")
        # 检查权限并尝试提升
        if not is_admin():
            messagebox.showwarning("权限不足", "脚本需要管理员权限来运行。尝试重新启动脚本...")
            restart_as_admin()
            sys.exit()

        # 创建框架
        self.frame = tk.Frame(root, padx=10, pady=10)
        self.frame.pack(fill=tk.BOTH, expand=True)

        # 源目录选择
        self.source_label = tk.Label(self.frame, text="源目录:")
        self.source_label.grid(row=0, column=0, padx=5, pady=5, sticky='w')
        self.source_entry = tk.Entry(self.frame, width=40)
        self.source_entry.grid(row=0, column=1, padx=5, pady=5)
        self.source_button = tk.Button(self.frame, text="浏览", command=self.select_source)
        self.source_button.grid(row=0, column=2, padx=5, pady=5)

        # 目标目录选择
        self.dest_label = tk.Label(self.frame, text="目标目录:")
        self.dest_label.grid(row=1, column=0, padx=5, pady=5, sticky='w')
        self.dest_entry = tk.Entry(self.frame, width=40)
        self.dest_entry.grid(row=1, column=1, padx=5, pady=5)
        self.dest_button = tk.Button(self.frame, text="浏览", command=self.select_dest)
        self.dest_button.grid(row=1, column=2, padx=5, pady=5)

        # 参数选择
        self.param_frame = tk.LabelFrame(self.frame, text="选择参数", padx=10, pady=10)
        self.param_frame.grid(row=2, column=0, columnspan=3, padx=10, pady=10, sticky='nsew')

        self.e_var = tk.BooleanVar()
        self.e_checkbox = tk.Checkbutton(self.param_frame, text="/E: 复制所有子目录，包括空目录", variable=self.e_var)
        self.e_checkbox.pack(anchor="w")

        self.m_var = tk.BooleanVar()
        self.m_checkbox = tk.Checkbutton(self.param_frame, text="/M: 只复制新增或修改过的文件", variable=self.m_var)
        self.m_checkbox.pack(anchor="w")

        self.z_var = tk.BooleanVar()
        self.z_checkbox = tk.Checkbutton(self.param_frame, text="/Z: 可重新启动模式", variable=self.z_var)
        self.z_checkbox.pack(anchor="w")

        self.zb_var = tk.BooleanVar()
        self.zb_checkbox = tk.Checkbutton(self.param_frame, text="/ZB: 可重新启动模式 + 备份模式", variable=self.zb_var)
        self.zb_checkbox.pack(anchor="w")

        self.mt_var = tk.BooleanVar()
        self.mt_checkbox = tk.Checkbutton(self.param_frame, text="/MT: 多线程复制（默认16线程）", variable=self.mt_var)
        self.mt_checkbox.pack(anchor="w")

        self.copyall_var = tk.BooleanVar()
        self.copyall_checkbox = tk.Checkbutton(self.param_frame, text="/COPYALL: 复制所有文件属性", variable=self.copyall_var)
        self.copyall_checkbox.pack(anchor="w")

        self.log_var = tk.BooleanVar()
        self.log_checkbox = tk.Checkbutton(self.param_frame, text="/LOG: 记录日志", variable=self.log_var)
        self.log_checkbox.pack(anchor="w")

        self.purge_var = tk.BooleanVar()
        self.purge_checkbox = tk.Checkbutton(self.param_frame, text="/PURGE: 删除目标中不再存在的文件", variable=self.purge_var)
        self.purge_checkbox.pack(anchor="w")

        self.mir_var = tk.BooleanVar()
        self.mir_checkbox = tk.Checkbutton(self.param_frame, text="/MIR: 镜像模式（等同于/E + /PURGE）", variable=self.mir_var)
        self.mir_checkbox.pack(anchor="w")

        self.xf_var = tk.StringVar()
        self.xf_label = tk.Label(self.param_frame, text="排除文件类型（如*.tmp *.bak）:")
        self.xf_label.pack(anchor="w")
        self.xf_entry = tk.Entry(self.param_frame, width=40, textvariable=self.xf_var)
        self.xf_entry.pack(anchor="w")

        self.xd_var = tk.StringVar()
        self.xd_label = tk.Label(self.param_frame, text="排除目录（如Dir1 Dir2）:")
        self.xd_label.pack(anchor="w")
        self.xd_entry = tk.Entry(self.param_frame, width=40, textvariable=self.xd_var)
        self.xd_entry.pack(anchor="w")

        # 执行按钮
        self.run_button = tk.Button(self.frame, text="执行Robocopy", command=self.run_robocopy)
        self.run_button.grid(row=3, column=0, columnspan=3, pady=20)

    def select_source(self):
        folder_selected = filedialog.askdirectory()
        self.source_entry.delete(0, tk.END)
        self.source_entry.insert(0, folder_selected)

    def select_dest(self):
        folder_selected = filedialog.askdirectory()
        self.dest_entry.delete(0, tk.END)
        self.dest_entry.insert(0, folder_selected)

    def run_robocopy(self):
        source = self.source_entry.get()
        dest = self.dest_entry.get()
        if not source or not dest:
            messagebox.showerror("错误", "源目录和目标目录不能为空！")
            return

        # 构建 robocopy 命令
        command = ["robocopy", source, dest]
        if self.e_var.get():
            command.append("/E")
        if self.m_var.get():
            command.append("/M")
        if self.z_var.get():
            command.append("/Z")
        if self.zb_var.get():
            command.append("/ZB")
        if self.mt_var.get():
            command.append("/MT:16")
        if self.copyall_var.get():
            command.append("/COPYALL")
        if self.log_var.get():
            log_path = r"C:\Logs"
            if not os.path.exists(log_path):
                os.makedirs(log_path)
            command.append(f"/LOG:{log_path}\\robocopy.log")
        if self.purge_var.get():
            command.append("/PURGE")
        if self.mir_var.get():
            command.append("/MIR")
        if self.xf_var.get():
            command.extend(["/XF"] + self.xf_var.get().split())
        if self.xd_var.get():
            command.extend(["/XD"] + self.xd_var.get().split())

        # 执行 robocopy 命令
        # 使用 subprocess.Popen 并设置 creationflags=subprocess.CREATE_NO_WINDOW
        process = subprocess.Popen(command, creationflags=subprocess.CREATE_NO_WINDOW, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        process.wait()  # 等待命令执行完成
            # 根据返回代码显示提示信息
        return_code = process.returncode
        if return_code == 0:
            messagebox.showinfo("成功", "Robocopy操作已完成！未复制任何文件。")
        elif return_code == 1:
            messagebox.showinfo("成功", "Robocopy操作已完成！所有文件已成功复制。")
        elif return_code == 2:
            messagebox.showwarning("警告", "目标目录中有额外的文件。未复制任何文件。")
        elif return_code == 3:
            messagebox.showwarning("警告", "Robocopy操作已完成！部分文件已复制，目标目录中有额外的文件。")
        elif return_code == 5:
            messagebox.showwarning("警告", "Robocopy操作已完成！部分文件已复制，存在不匹配的文件。")
        elif return_code == 6:
            messagebox.showwarning("警告", "目标目录中有额外的文件和不匹配的文件。未复制任何文件。")
        elif return_code == 7:
            messagebox.showwarning("警告", "Robocopy操作已完成！部分文件已复制，存在不匹配的。")
        elif return_code >= 8:
            messagebox.showerror("错误", f"Robocopy操作失败！返回代码：{return_code}")
            
if __name__ == "__main__":
    root = tk.Tk()
    app = RobocopyGUI(root)
    root.mainloop()
